import * as jwt from 'jsonwebtoken';
import { config } from '@/config';
import { UnauthorizedException } from '@nestjs/common';
const { secret, expire, issuer, alg } = config.jwt;
/**
 * 根据参数生成token
 * @param data
 */
export const generateToken = async (data: object | string): Promise<string> => {
  return new Promise((resolve, reject) =>
    jwt.sign(
      { data },
      secret,
      {
        expiresIn: expire,
        issuer: issuer,
        algorithm: alg,
      },
      (err, encoded) => (err ? reject(err) : resolve(encoded)),
    ),
  );
};
/**
 * 根据token解密,获取数据
 * @param token
 */
const verify = async (token: string): Promise<any> => {
  return new Promise((resolve, reject) =>
    jwt.verify(
      token,
      secret,
      {
        issuer: issuer,
        algorithms: [alg],
      },
      (err, decoded) => (err ? reject(err) : resolve(decoded)),
    ),
  );
};

/**
 * 
 * @param token {
  data: { name: 'wangjing', password: 'wangjing123' },
  iat: 1637734290,
  exp: 1637737890,
  iss: 'wangjing'
}
 */

export const getUserFromToken = async (token: string): Promise<any> => {
  try {
    // 1: 验证token是否有效，等有效后再解码
    const r = await verify(token);
    // const { data } = res. ; // const { data } = res;
    console.log(r.data);
    const { data, iss } = r;
    // 验证签发人是否和配置里的一致
    if (iss !== issuer) {
      throw new UnauthorizedException('无效token:token签发错误');
    }
    return data;
  } catch (error) {
    console.log(error);
    throw new UnauthorizedException(error);
  }
};
